package com.fz.service.impl;

import com.fz.controller.request.BaseRequest;
import com.fz.mapper.BookMapper;
import com.fz.mapper.BorrowMapper;
import com.fz.mapper.ReturnBooksMapper;
import com.fz.mapper.UserMapper;
import com.fz.pojo.Book;
import com.fz.pojo.Borrow;
import com.fz.pojo.ReturnBooks;
import com.fz.pojo.User;
import com.fz.service.ReturnService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
@Slf4j
public class ReturnServiceImpl implements ReturnService {
    @Autowired
    private ReturnBooksMapper returnBooksMapper;

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<ReturnBooks> pageReturn(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<ReturnBooks> books = returnBooksMapper.listReturnByCondition(baseRequest);
        return new PageInfo<>(books);
    }

    @Override
    @Transactional
    public void addReturn(ReturnBooks returnBooks) {
        //改状态
        returnBooks.setStatus("已归还");
        borrowMapper.updateStatus("已归还", returnBooks.getId());//returnBooks.getId()是前端传来的借书id


        returnBooks.setRealDate(LocalDate.now());
        returnBooksMapper.addReturn(returnBooks);
        //图书数量增加
        bookMapper.updateNumByNo(returnBooks.getBookNo());

        //返还和扣除用户金额  根据应该还书日期和实际还书日期返还一定的金额
        Book book = bookMapper.getByNo(returnBooks.getBookNo());
        if (book != null) {
            long until = 0;
            if (returnBooks.getRealDate().isBefore(returnBooks.getReturnDate())) {//提前还书退还金额
                until = returnBooks.getRealDate().until(returnBooks.getReturnDate(), ChronoUnit.DAYS);
            } else if (returnBooks.getRealDate().isAfter(returnBooks.getReturnDate())) {//没在指定日期归还 要扣除一定的金额
                until = -returnBooks.getReturnDate().until(returnBooks.getRealDate(), ChronoUnit.DAYS);
            }
            int score = (int) until * book.getScore(); //获取待归还的金额或扣除的金额
            User user = userMapper.getByUsername(returnBooks.getUserNo());
            int account = user.getAccount() + score;//余额加上扣除的金额
            user.setAccount(account);
            if (account < 0) {
                    //锁定账户
                    user.setStatus(false);
            }
            userMapper.updateById(user);
        }


    }

    @Override
    public void deleteReturnById(Integer id) {
        returnBooksMapper.deleteReturnById(id);
    }
}
